<?php
namespace app\user\controller;

use app\admin\model\user\User;
use app\common\controller\Home;
use think\facade\Cookie;
use think\facade\Session;

class Login extends Home
{
    public function index()
    {
        if($this->request->post())
        {
            $input = $this->request->post();
            //空用户
            if(!$input['username']) $this->error("请输入账户，或者手机号");
            //空密码
            if(!$input['password']) $this->error("请输入密码");
            //nc_token
            //if($input['nc_token']!=session("NC_TOKEN")||!$input['nc_token']) $this->error("请滑动验证条进行验证");

            $user = (new User())->where("username",$input['username'])->find();

            if(!$user) $this->error("用户不存在请稍后再试");

            if(!PasswordVerify($input['password'],$user['password']))  $this->error("密码错误");


            unset($user['password']);
            cmf_generate_user_token($user["id"], 'web');

            Cookie::set("user",$user);
           /* session("user",$user);
            Session::delete("NC_TOKEN");*/

            $this->success("正在登录系统请稍后",'',$input);
        }
        return $this->fetch();
    }

    //发送邮政验证码
    public function send_email_code()
    {
       if(is_open_register() != 1) $this->error("error");

       $email = $this->request->param("email");
       if(!valiDateEmail($email)) $this->error("电子邮件格式错");

        $code =mt_rand(1111,9999);

        /**
         * 下发电子邮件验证码
         */
        $emailTemplateConfig = get_option("email_template_verification_code");
        $emailTemplateConfig['template'] = str_replace('{$code}',$code,$emailTemplateConfig['template']);

        $res =  send_email($email,$emailTemplateConfig['subject'],$emailTemplateConfig['template']);

        if($res['error']==0)
        {
            cache($email."_email_code",$code,3600);
            $this->success("验证码已下发到你的邮件，请注意查收");
        }else{
            $this->error("发送失败，请稍后再试");
        }
    }
}